package my.rpc.spring;

import my.rpc.client.RpcClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * 客户端根据xml配置的reference标签解析出服务器端传递过来的实现类
 * @author fengbo
 * @date 2017/11/16
 */
public class Reference<T> implements FactoryBean<T>, InitializingBean, DisposableBean {

    private static final Logger log = LoggerFactory.getLogger(Reference.class);

    private String interfaceName;
    private String url;

    @Override
    public T getObject() {
        return RpcClient.getInstance().create(getObjectType(), url);
    }

    @Override
    public Class<?> getObjectType() {
        try {
            return this.getClass().getClassLoader().loadClass(interfaceName);
        } catch (ClassNotFoundException e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() {
        RpcClient.getInstance().load(url);
    }

    @Override
    public void destroy() {
        RpcClient.getInstance().unLoad(url);
    }

    public void setInterfaceName(String interfaceName) {
        this.interfaceName = interfaceName;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
